package com.jakewharton.rxbinding4.component;

import static com.jakewharton.rxbinding4.internal.Preconditions.checkMainThread;

import com.jakewharton.rxbinding4.InitialValueObservable;

import io.reactivex.rxjava3.annotations.Nullable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.openharmony.MainThreadDisposable;
import ohos.agp.components.Slider;

final class SeekBarUpdateObservable extends InitialValueObservable<Integer> {
    private final Slider view;

    @Nullable
    private final Boolean shouldBeFromUser;

    SeekBarUpdateObservable(Slider view, @Nullable Boolean shouldBeFromUser) {
        this.view = view;
        this.shouldBeFromUser = shouldBeFromUser;
    }

    @Override
    protected void subscribeListener(Observer<? super Integer> observer) {
        if (!checkMainThread(observer)) {
            return;
        }
        Listener listener = new Listener(view, shouldBeFromUser, observer);
        view.setValueChangedListener(listener);
        observer.onSubscribe(listener);
    }

    @Override
    protected Integer getInitialValue() {
        return view.getProgress();
    }

    static final class Listener extends MainThreadDisposable implements Slider.ValueChangedListener {
        private final Slider view;
        private final Boolean shouldBeFromUser;
        private final Observer<? super Integer> observer;

        Listener(Slider view, Boolean shouldBeFromUser, Observer<? super Integer> observer) {
            this.view = view;
            this.shouldBeFromUser = shouldBeFromUser;
            this.observer = observer;
        }

        @Override
        protected void onDispose() {
            view.setValueChangedListener(null);
        }

        @Override
        public void onProgressUpdated(Slider slider, int progress, boolean fromUser) {
            if (!isDisposed() && (shouldBeFromUser == null || shouldBeFromUser == fromUser)) {
                observer.onNext(progress);
            }
        }

        @Override
        public void onTouchStart(Slider slider) {}

        @Override
        public void onTouchEnd(Slider slider) {}
    }
}
